package ar.com.spsolutions.splilabrary.view.pages.book;// NOPMD

import org.apache.log4j.Logger;
import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.WindowClosedCallback;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.request.resource.ContextRelativeResource;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.odlabs.wiquery.core.effects.EffectBehavior;
import org.odlabs.wiquery.core.effects.basic.Hide;
import org.odlabs.wiquery.core.effects.sliding.SlideToggle;
import org.odlabs.wiquery.core.events.Event;
import org.odlabs.wiquery.core.events.MouseEvent;
import org.odlabs.wiquery.core.events.WiQueryEventBehavior;
import org.odlabs.wiquery.core.javascript.JsScope;
import org.odlabs.wiquery.core.javascript.JsStatement;

import ar.com.spsolutions.splibrary.book.Book;
import ar.com.spsolutions.splibrary.services.BookService;
import ar.com.spsolutions.splibrary.services.LibraryServiceFacade;
import ar.com.spsolutions.splibrary.user.User;
import ar.com.spsolutions.splilabrary.view.application.WebSession;
import ar.com.spsolutions.splilabrary.view.components.modalwindow.SelectModalWindow;

public class BookDetail extends Panel {

    private static final long serialVersionUID = -3714564658972730880L;

    protected static final Logger LOG = Logger.getLogger(BookDetail.class.getCanonicalName());

    @SpringBean
    private LibraryServiceFacade libraryServiceFacade;

    private boolean available;

    private Book book;

    private static Book reserveBook;

    private static User reserveUser;

    private static BookService bookService;

    private ModalWindow modal1;

    private SelectModalWindow feedbackModalWindow;

    // private BookCommentContainer bookCommentContainer;

    public BookDetail(final String id, final Book aBook) {
        super(id);
        setBook(aBook);
        setOutputMarkupId(true);
        initialize();

    }

    private void initialize() {
        available = bookService().isAvailable(book);
        final Form<Book> form = new Form<Book>("descriptionForm", new CompoundPropertyModel<Book>(getBook()));
        form.add(new Label("title"));
        form.add(new Label("author"));
        form.add(new Label("isbn"));
        form.add(new Label("publisher"));
        form.add(new TextArea<Book>("description").setEnabled(false));
        createStars(form);
        form.add(new Label("starCounter"));
        // form.add(getLoanButton().add(
        // new PrettyPopinBehavior(new
        // PrettyPopinOptions().width(500).height(400).followScroll(false))));
        form.add(getLoanButton());
        modal1 = new ModalWindow("modal1");
        form.add(modal1);

        modal1.setCookieName("modal-1");

        modal1.setPageCreator(new ModalWindow.PageCreator() {
            private static final long serialVersionUID = 4449689936181947298L;

            @Override
            public LoanModalWindow createPage() {
                return new LoanModalWindow(BookDetail.this.getWebPage().getPageReference(), modal1);
            }
        });
        modal1.setWindowClosedCallback(new WindowClosedCallback() {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClose(final AjaxRequestTarget target) {
                // target.add(result);
            }
        });
        modal1.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean onCloseButtonClicked(final AjaxRequestTarget target) {
                // setResult("Modal window 1 - close button");
                return true;
            }
        });

        final String pic = book.getPic() == null ? "bookPic/Libro X.jpg" : book.getPic();
        form.add(new Image("pic", new ContextRelativeResource(pic)));

        getCommentLink(form);

        feedbackModalWindow = new SelectModalWindow("feedback");
        form.add(feedbackModalWindow);

        this.add(form);

    }

    private void getCommentLink(final Form<Book> form) {
        final WebMarkupContainer hideTextOnLoad = new WebMarkupContainer("commentList");
        if (book.getComments().isEmpty()) {
            hideTextOnLoad.add(new BookCommentPanelContainer("commentPanel"));
        } else {
            hideTextOnLoad.add(new BookCommentPanelContainer("commentPanel", book.getComments()));
        }
        hideTextOnLoad.add(new EffectBehavior(new Hide()));
        form.add(hideTextOnLoad);

        // Show / Hide a text with the slide effect
        final WebMarkupContainer button = new WebMarkupContainer("commentLink");
        button.add(new WiQueryEventBehavior(new Event(MouseEvent.CLICK) {
            private static final long serialVersionUID = 1L;

            @Override
            public JsScope callback() {
                return JsScope.quickScope(new JsStatement().$(BookDetail.this, "#commentList").chain(new SlideToggle())
                        .render());
            }
        }));
        form.add(button);
    }

    private AjaxLink<Void> getLoanButton() {
        final AjaxLink<Void> link = new AjaxLink<Void>("loanButton") {

            private static final long serialVersionUID = -3806415394925956783L;

            @Override
            public void onClick(final AjaxRequestTarget target) {
                final LibraryServiceFacade service = BookDetail.this.getLibraryServiceFacade();
                final User user = ((WebSession) Session.get()).getUser();

                if (BookDetail.this.isAvailable() && BookDetail.this.canRentAnotherBook()) {
                    service.createLoanFor(user, BookDetail.this.getBook());
                    feedbackModalWindow.show(target);
                    // this.setResponsePage(Home.class);

                } else {
                    BookDetail.reserveUser = user;
                    BookDetail.reserveBook = book;
                    BookDetail.bookService = service.getEntityService().getBookService();
                    modal1.show(target);
                }

            }
        };
        link.setVisible(((WebSession) Session.get()).getUser() != null);
        return link;
    }

    private boolean canRentAnotherBook() {
        return (getUser() != null) && getUser().canRentAnotherBook();
    }

    private User getUser() {
        return ((WebSession) getSession()).getUser();
    }

    private void createStars(final Form<Book> form) {
        final Link<?> star1 = new Link<Object>("star1") {
            private static final long serialVersionUID = -5307657564288354596L;

            @Override
            public void onClick() {
                BookDetail.this.getBook().getStarCounter().addOneStar();
            }
        };
        form.add(star1);
        final Link<?> star2 = new Link<Object>("star2") {
            private static final long serialVersionUID = 5677677091315321678L;

            @Override
            public void onClick() {
                BookDetail.this.getBook().getStarCounter().addTwoStar();
            }
        };
        form.add(star2);

        final Link<?> star3 = new Link<Object>("star3") {
            private static final long serialVersionUID = 6513002050600089460L;

            @Override
            public void onClick() {
                BookDetail.this.getBook().getStarCounter().addThreeStar();
            }
        };
        form.add(star3);

        final Link<?> star4 = new Link<Object>("star4") {
            private static final long serialVersionUID = -6378469022686462192L;

            @Override
            public void onClick() {
                BookDetail.this.getBook().getStarCounter().addFourStar();
            }
        };
        form.add(star4);

        final Link<?> star5 = new Link<Object>("star5") {
            private static final long serialVersionUID = -2329884743903458L;

            @Override
            public void onClick() {
                BookDetail.this.getBook().getStarCounter().addFiveStar();
            }
        };
        form.add(star5);

    }

    public LibraryServiceFacade getLibraryServiceFacade() {
        return libraryServiceFacade;
    }

    public void setLibraryServiceFacade(final LibraryServiceFacade libraryServiceFacade) {
        this.libraryServiceFacade = libraryServiceFacade;
    }

    public boolean isAvailable() {
        return available;
    }

    public void setAvailable(final boolean available) {
        this.available = available;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(final Book book) {
        this.book = book;
    }

    private BookService bookService() {
        return getLibraryServiceFacade().getEntityService().getBookService();
    }

    public static Book getReserveBook() {
        return BookDetail.reserveBook;
    }

    public static User getReserveUser() {
        return BookDetail.reserveUser;
    }

    public static BookService getBookService() {
        return BookDetail.bookService;
    }

}
